﻿// © 2009 Microsoft Corporation.  All rights reserved.

#region Namespaces

using System;
using System.Collections.Generic;
using System.IdentityModel;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.Linq;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Web;

using Microsoft.InformationSecurity.CISF.Security;
using Microsoft.InformationSecurity.CISF.Security.AuthZServices;

#endregion

/// This namespace has class definition for the Authorization Action.
namespace Microsoft.InformationSecurity.Risk.AuthorizationManager
{
    /// <summary>
    /// The class implements authenication for Service Layer based on CISF prinicipal.
    /// </summary>
    public class AuthorizationAction : IAuthorizationPolicy
    {
        Guid id = Guid.NewGuid();

        // this method gets called after the authentication stage
        public bool Evaluate(EvaluationContext evaluationContext, ref object state)
        {            
                // Get the authenticated client identity
                IIdentity client = GetClientIdentity(evaluationContext);
                
                Microsoft.InformationSecurity.CISF.Security.AuthZServices.AuthZService auth = new AuthZService();
                User singleuser = auth.GetUserInformation(client.Name);

                // Set the custom principal
                evaluationContext.Properties["Principal"] = new CISF.Security.Principal.CISFPrincipal(client, singleuser);                            
                return true;
        }

        private IIdentity GetClientIdentity(EvaluationContext evaluationContext)
        {
            object obj;
            if (!evaluationContext.Properties.TryGetValue("Identities", out obj))
                throw new Exception("No Identity found");

            IList<IIdentity> identities = obj as IList<IIdentity>;
            if (identities == null || identities.Count <= 0)
                throw new Exception("No Identity found");

            return identities[0];
        }


        #region IAuthorizationPolicy Members


        public ClaimSet Issuer
        {
            get { throw new NotImplementedException(); }
        }

        #endregion

        #region IAuthorizationComponent Members

        public string Id
        {
            get { return id.ToString(); }
        }

        #endregion
    } 
}
